package com.cblue.qimokao.controller;


import com.cblue.qimokao.entity.User;
import com.cblue.qimokao.service.UserService;
import com.cblue.qimokao.vo.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest request){
        User iExistuser = userService.selectByUser(user);
        if(iExistuser!=null){
            //保存一条redis数据
            redisTemplate.boundValueOps(user.getUsername()).set("logined");
            request.getSession().setAttribute("username",user.getUsername());
            return new Result();
        }else{
            return new Result(2,"用户名或密码错误");
        }
    }

    @RequestMapping("/autoLogin")
    public Result autoLogin(String username){
        if(username!=null){
            String result  = (String)redisTemplate.boundValueOps(username).get();
            if("logined".equals(result)){
                return new Result();
            }
        }
        return new Result(2,"自动登录失败");
    }

    @RequestMapping("/cool")
    public Result cool(String username){

        return new Result(0,"so cool");
    }


}
